package com.su.sweet.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.su.sweet.model.SUserRole;
import com.su.sweet.service.ISUserRoleService;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@Mapping("/sUserRole")
public class SUserRoleController {
    @Inject
    private ISUserRoleService userRoleService;

    /**
     * 为用户分配角色(先删除已有绑定再重新绑定)
     */
    @Post
    @Mapping("/assign")
    public Result assignRole(Context ctx, SUserRole userRole) {
        // 先删除用户已有的该角色绑定
        userRoleService.lambdaUpdate()
                .eq(SUserRole::getUserId, userRole.getUserId())
                .remove();

        // 创建新的绑定
        userRole.setCreateTime(LocalDateTime.now());
        userRole.setCreateUser(Long.valueOf(ctx.header("userId")));
        return Result.succeed(userRoleService.save(userRole));
    }

    /**
     * 移除用户的角色
     */
    @Post
    @Mapping("/remove")
    public Result removeRole(SUserRole userRole) {
        return Result.succeed(userRoleService.remove(new QueryWrapper<SUserRole>()
                .eq("role_id", userRole.getRoleId())
                .eq("user_id", userRole.getUserId())));
    }

    /**
     * 查询用户的角色列表
     */
    @Get
    @Mapping("/userRoles")
    public Result getUserRoles(Long userId) {
        return Result.succeed(userRoleService.lambdaQuery()
                .eq(SUserRole::getUserId, userId)
                .list());
    }

    /**
     * 查询角色的用户列表
     */
    @Get
    @Mapping("/roleUsers")
    public Result getRoleUsers(Long roleId) {
        return Result.succeed(userRoleService.lambdaQuery()
                .eq(SUserRole::getRoleId, roleId)
                .list());
    }
}
